<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>多语言翻译工具</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Arial', sans-serif;
        }
        
        body {
            background-color: #f5f7fa;
            color: #333;
            line-height: 1.6;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        header {
            text-align: center;
            margin-bottom: 30px;
            padding: 20px 0;
        }
        
        h1 {
            color: #2c3e50;
            font-size: 2.5rem;
            margin-bottom: 10px;
        }
        
        .subtitle {
            color: #7f8c8d;
            font-size: 1.1rem;
        }
        
        .main-content {
            display: flex;
            flex-direction: column;
            gap: 30px;
        }
        
        .input-section {
            background-color: white;
            border-radius: 10px;
            padding: 25px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .input-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        
        .input-header h2 {
            color: #2c3e50;
            font-size: 1.5rem;
        }
        
        .char-count {
            color: #7f8c8d;
            font-size: 0.9rem;
        }
        
        .source-language {
            margin-bottom: 15px;
        }
        
        .source-language label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        .source-language select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 1rem;
        }
        
        #input-text {
            width: 100%;
            height: 150px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 1rem;
            resize: vertical;
        }
        
        .control-panel {
            background-color: white;
            border-radius: 10px;
            padding: 25px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .control-panel h2 {
            color: #2c3e50;
            font-size: 1.5rem;
            margin-bottom: 15px;
        }
        
        .target-languages {
            margin-bottom: 20px;
        }
        
        .target-languages h3 {
            margin-bottom: 10px;
            color: #34495e;
        }
        
        .language-options {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 10px;
        }
        
        .language-option {
            display: flex;
            align-items: center;
        }
        
        .language-option input {
            margin-right: 8px;
        }
        
        .action-buttons {
            display: flex;
            gap: 15px;
        }
        
        .btn {
            padding: 12px 25px;
            border: none;
            border-radius: 5px;
            font-size: 1rem;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        
        .btn-primary {
            background-color: #3498db;
            color: white;
        }
        
        .btn-primary:hover {
            background-color: #2980b9;
        }
        
        .btn-secondary {
            background-color: #e74c3c;
            color: white;
        }
        
        .btn-secondary:hover {
            background-color: #c0392b;
        }
        
        .btn-success {
            background-color: #2ecc71;
            color: white;
        }
        
        .btn-success:hover {
            background-color: #27ae60;
        }
        
        .output-section {
            background-color: white;
            border-radius: 10px;
            padding: 25px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .output-section h2 {
            color: #2c3e50;
            font-size: 1.5rem;
            margin-bottom: 20px;
        }
        
        .results-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
        }
        
        .result-card {
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
            position: relative;
        }
        
        .result-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
            padding-bottom: 8px;
            border-bottom: 1px solid #eee;
        }
        
        .language-name {
            font-weight: bold;
            color: #2c3e50;
            display: flex;
            align-items: center;
        }
        
        .flag {
            margin-right: 8px;
            font-size: 1.2rem;
        }
        
        .copy-btn {
            background-color: #2ecc71;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 5px 10px;
            cursor: pointer;
            font-size: 0.8rem;
        }
        
        .copy-btn:hover {
            background-color: #27ae60;
        }
        
        .result-text {
            min-height: 100px;
            line-height: 1.5;
        }
        
        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }
        
        .loading-spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #3498db;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 2s linear infinite;
            margin: 0 auto 10px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .empty-state {
            text-align: center;
            padding: 40px;
            color: #7f8c8d;
        }
        
        @media (max-width: 768px) {
            .container {
                padding: 15px;
            }
            
            h1 {
                font-size: 2rem;
            }
            
            .action-buttons {
                flex-direction: column;
            }
            
            .btn {
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>多语言翻译工具</h1>
            <p class="subtitle">输入一种语言，同时翻译成多种语言</p>
        </header>
        
        <main class="main-content">
            <section class="input-section">
                <div class="input-header">
                    <h2>输入文本</h2>
                    <div class="char-count">字数: <span id="char-count">0</span></div>
                </div>
                
                <div class="source-language">
                    <label for="source-lang">源语言</label>
                    <select id="source-lang">
                        <option value="auto">自动检测</option>
                        <option value="zh">中文</option>
                        <option value="en">英语</option>
                        <option value="ko">韩语</option>
                        <option value="ja">日语</option>
                        <option value="fr">法语</option>
                        <option value="de">德语</option>
                        <option value="es">西班牙语</option>
                        <option value="ru">俄语</option>
                        <option value="vi">越南语</option>
                        <option value="ar">阿拉伯语</option>
                    </select>
                </div>
                
                <textarea id="input-text" placeholder="请输入要翻译的文本..."></textarea>
            </section>
            
            <section class="control-panel">
                <h2>翻译设置</h2>
                
                <div class="target-languages">
                    <h3>选择目标语言</h3>
                    <div class="language-options">
                        <div class="language-option">
                            <input type="checkbox" id="lang-zh" value="zh" checked>
                            <label for="lang-zh">中文</label>
                        </div>
                        <div class="language-option">
                            <input type="checkbox" id="lang-en" value="en" checked>
                            <label for="lang-en">英语</label>
                        </div>
                        <div class="language-option">
                            <input type="checkbox" id="lang-ko" value="ko">
                            <label for="lang-ko">韩语</label>
                        </div>
                        <div class="language-option">
                            <input type="checkbox" id="lang-ja" value="ja">
                            <label for="lang-ja">日语</label>
                        </div>
                        <div class="language-option">
                            <input type="checkbox" id="lang-fr" value="fr">
                            <label for="lang-fr">法语</label>
                        </div>
                        <div class="language-option">
                            <input type="checkbox" id="lang-de" value="de">
                            <label for="lang-de">德语</label>
                        </div>
                        <div class="language-option">
                            <input type="checkbox" id="lang-es" value="es">
                            <label for="lang-es">西班牙语</label>
                        </div>
                        <div class="language-option">
                            <input type="checkbox" id="lang-ru" value="ru">
                            <label for="lang-ru">俄语</label>
                        </div>
                        <div class="language-option">
                            <input type="checkbox" id="lang-vi" value="vi">
                            <label for="lang-vi">越南语</label>
                        </div>
                        <div class="language-option">
                            <input type="checkbox" id="lang-ar" value="ar">
                            <label for="lang-ar">阿拉伯语</label>
                        </div>
                    </div>
                </div>
                
                <div class="action-buttons">
                    <button class="btn btn-primary" id="translate-btn">翻译</button>
                    <button class="btn btn-secondary" id="clear-btn">清空</button>
                    <button class="btn btn-success" id="export-btn" style="display: none;">导出Excel</button>
                </div>
            </section>
            
            <section class="output-section">
                <h2>翻译结果</h2>
                
                <div class="loading" id="loading">
                    <div class="loading-spinner"></div>
                    <p>正在翻译中，请稍候...</p>
                </div>
                
                <div class="results-container" id="results-container">
                    <div class="empty-state">
                        <p>请输入文本并选择目标语言，然后点击翻译按钮</p>
                    </div>
                </div>
            </section>
        </main>
    </div>

    <script>
        // 语言名称和对应的旗帜
        const languageInfo = {
            'zh': { name: '中文', flag: '🇨🇳' },
            'en': { name: '英语', flag: '🇺🇸' },
            'ko': { name: '韩语', flag: '🇰🇷' },
            'ja': { name: '日语', flag: '🇯🇵' },
            'fr': { name: '法语', flag: '🇫🇷' },
            'de': { name: '德语', flag: '🇩🇪' },
            'es': { name: '西班牙语', flag: '🇪🇸' },
            'ru': { name: '俄语', flag: '🇷🇺' },
            'vi': { name: '越南语', flag: '🇻🇳' },
            'ar': { name: '阿拉伯语', flag: '🇸🇦' }
        };

        // 获取DOM元素
        const inputText = document.getElementById('input-text');
        const charCount = document.getElementById('char-count');
        const translateBtn = document.getElementById('translate-btn');
        const clearBtn = document.getElementById('clear-btn');
        const exportBtn = document.getElementById('export-btn');
        const resultsContainer = document.getElementById('results-container');
        const loading = document.getElementById('loading');
        
        // 存储最近的翻译结果
        let lastTranslationResults = null;
        let lastSourceLang = null;
        let lastOriginalText = null;

        // 更新字数统计
        inputText.addEventListener('input', function() {
            charCount.textContent = this.value.length;
        });

        // 清空按钮功能
        clearBtn.addEventListener('click', function() {
            inputText.value = '';
            charCount.textContent = '0';
            resultsContainer.innerHTML = '<div class="empty-state"><p>请输入文本并选择目标语言，然后点击翻译按钮</p></div>';
            exportBtn.style.display = 'none';
            lastTranslationResults = null;
            lastSourceLang = null;
            lastOriginalText = null;
        });

        // 翻译按钮功能
        translateBtn.addEventListener('click', async function() {
            const text = inputText.value.trim();
            
            if (!text) {
                alert('请输入要翻译的文本');
                return;
            }
            
            // 获取选中的目标语言
            const selectedLanguages = [];
            const checkboxes = document.querySelectorAll('.language-option input[type="checkbox"]:checked');
            
            if (checkboxes.length === 0) {
                alert('请至少选择一种目标语言');
                return;
            }
            
            checkboxes.forEach(checkbox => {
                selectedLanguages.push(checkbox.value);
            });
            
            // 获取源语言
            const sourceLang = document.getElementById('source-lang').value;
            
            // 显示加载状态
            loading.style.display = 'block';
            resultsContainer.innerHTML = '';
            
            try {
                // 调用后端翻译API
                const response = await fetch('/api/translate', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        text: text,
                        sourceLang: sourceLang,
                        targetLangs: selectedLanguages
                    })
                });
                
                if (!response.ok) {
                    throw new Error('翻译请求失败');
                }
                
                const data = await response.json();
                
                if (data.success) {
                    // 保存翻译结果用于导出
                    lastTranslationResults = data.results;
                    lastSourceLang = sourceLang;
                    lastOriginalText = text;
                    
                    displayResults(data.results);
                    // 显示导出Excel按钮
                    exportBtn.style.display = 'inline-block';
                } else {
                    throw new Error(data.error || '翻译失败');
                }
                
            } catch (error) {
                console.error('翻译错误:', error);
                resultsContainer.innerHTML = `<div class="empty-state"><p>翻译失败: ${error.message}</p></div>`;
            } finally {
                loading.style.display = 'none';
            }
        });

        // 显示翻译结果
        function displayResults(translationResults) {
            resultsContainer.innerHTML = '';
            
            // 遍历翻译结果
            Object.keys(translationResults).forEach(lang => {
                const translatedText = translationResults[lang];
                
                const resultCard = document.createElement('div');
                resultCard.className = 'result-card';
                
                const header = document.createElement('div');
                header.className = 'result-header';
                
                const languageName = document.createElement('div');
                languageName.className = 'language-name';
                languageName.innerHTML = `<span class="flag">${languageInfo[lang].flag}</span>${languageInfo[lang].name}`;
                
                const copyBtn = document.createElement('button');
                copyBtn.className = 'copy-btn';
                copyBtn.textContent = '复制';
                copyBtn.addEventListener('click', function() {
                    const textToCopy = resultText.textContent;
                    navigator.clipboard.writeText(textToCopy)
                        .then(() => {
                            copyBtn.textContent = '已复制';
                            setTimeout(() => {
                                copyBtn.textContent = '复制';
                            }, 2000);
                        })
                        .catch(err => {
                            console.error('无法复制文本: ', err);
                        });
                });
                
                header.appendChild(languageName);
                header.appendChild(copyBtn);
                
                const resultText = document.createElement('div');
                resultText.className = 'result-text';
                // 保持原文的排版格式（换行、空格等）
                resultText.style.whiteSpace = 'pre-wrap';
                resultText.textContent = translatedText;
                
                resultCard.appendChild(header);
                resultCard.appendChild(resultText);
                resultsContainer.appendChild(resultCard);
            });
        }

        // 导出Excel按钮功能
        exportBtn.addEventListener('click', async function() {
            if (!lastTranslationResults || !lastOriginalText) {
                alert('没有可导出的翻译结果');
                return;
            }

            try {
                // 调用后端Excel导出API
                const response = await fetch('/api/export-excel', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        originalText: lastOriginalText,
                        sourceLang: lastSourceLang,
                        translationResults: lastTranslationResults
                    })
                });

                if (!response.ok) {
                    throw new Error('Excel导出请求失败');
                }

                // 获取文件名
                const contentDisposition = response.headers.get('Content-Disposition');
                let filename = 'translation_results.xlsx';
                
                if (contentDisposition) {
                    const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
                    if (filenameMatch && filenameMatch[1]) {
                        filename = filenameMatch[1].replace(/['"]/g, '');
                    }
                }

                // 将响应转换为Blob并下载
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = url;
                a.download = filename;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);

            } catch (error) {
                console.error('Excel导出错误:', error);
                alert(`Excel导出失败: ${error.message}`);
            }
        });
    </script>
</body>
</html>